package concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Mr.Sun
 * @date 2022年09月03日 21:52
 *
 * 校验偶数的有效性
 *
 * <p>
 *     一个任务产生产生偶数，而其他任务消费这些数字。而这些消费者任务的唯一工作就是校验偶数的有效性
 * </p>
 */
public class EventChecker implements Runnable {

    private IntGenerator generator;
    private final int id;

    public EventChecker(IntGenerator generator, int id) {
        this.generator = generator;
        this.id = id;
    }

    @Override
    public void run() {
        while (!generator.isCanceled()) {
            int val = generator.next();
            if (val % 2 != 0) {
                System.out.println(val + " not event");
                // 取消 事件检查
                generator.cancel();
            }
        }
    }

    public static void test(IntGenerator gp, int count) {
        System.out.println("按 Ctrl + C 退出");
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < count; i++) {
            exec.execute(new EventChecker(gp, i));
        }
        exec.shutdown();
    }

    public static void test(IntGenerator gp) {
        // count 默认值
        test(gp, 10);
    }
}
